<?php

namespace RedMVC;

/**
 * Translate class
 *  
 * @category    RedMVC
 * @author      Jan Fischer, bitWorking <info@bitworking.de>
 */
class Translate{

    protected $_data = array();
    protected $_dataFlipped;

    public function __construct(){
        
    }

    /**
     * set the translation data
     *
     * @param array|string $data file name or array
     */
    public function setData($data){
        if(!is_array($data)){
            if(file_exists($data)){
                ob_start();
                $data = include($data);
                ob_end_clean();
            }
        }
        if(!is_array($data)){
            throw new \Exception("Translate: data is no valid file or array");
        }
        $this->_data = $data;
    }

    /**
     * try to translate the given key
     *
     * @param string $key
     * @return string
     */
    public function _($key){
        if(array_key_exists($key, $this->_data)){
            $value = $this->_data[$key];
            if(!empty($value)){
                return $value;
            }
            return $key;
        }
        return $key;
    }
    
    /**
     * flipped translation (for router)
     *
     * @param string $key
     * @return string
     */
    public function __($key){
        if(null === $this->_dataFlipped){
            $this->_dataFlipped = array_flip($this->_data);
        }
        if(array_key_exists($key, $this->_dataFlipped)){
            $value = $this->_dataFlipped[$key];
            if(!empty($value)){
                return $value;
            }
            return $key;
        }
        return $key;
    }

}